from flask import Flask, render_template, request,jsonify,escape
import requests
import json



app = Flask(__name__)

def log_request(req:"flask request",res:str):
 with open("vsearch.log","a") as log:
  print(req.form,req.host_url,req.remote_addr,res,file=log,sep="|")


#def hello() -> str:
 #return "hello wrold"


#@app.route('/search',methods = ['POST','GET'])
#def search():
 #phrase = request.form.get("phrase")
 #letters = request.form.get("letters")
 #results = phrase + letters
 #log_request(request,results)
 #title = "Here are your results"
 #return render_template("results.html",the_title=title,the_phrase=phrase,the_letters=letters,the_results=results)


@app.route("/entry",methods = ['POST','GET'])
def entry():
	user = request.form.get("user")
	log_request(request,user)
	return render_template('entry.html',the_title='植物辨别')

@app.route("/login",methods = ['GET'])
def index():
 	title = 'hello'
 	return render_template("login.html",the_title=title)

@app.route("/remote",methods=['POST'])
def remote():
 	image_url=request.form['remote']
 	endpoint = "https://cvhzx.cognitiveservices.azure.com/"
 	subscription_key = "uZK7pb2gSB5FPGEHIjBvjiUS"
 	analyze_url = enpoint + "vision/v3.1/analyze"
 	headers = {'Ocp-Apim-Subscription-Key': subscription_key}
 	params = {'visualFeatures': 'Categories,Description,Color'}
 	data = {'url': image_url}
 	response = requests.post(analyze_url, headers=headers, params=params, json=data)
 	response.raise_for_states()
 	analysis = response.json()
 	print(json.dump(response.json))
 	image_caption = analysis["description"]["captions"][0]["text"].capitalize()
 	confidence3 = analysis["description"]["captions"][0]["confidence"]
 	return render_template('entry.html',remote=str(image_caption),confidence3=str(confidence3),img_url1=image_url)

@app.route("/viewlog")
def view_log():
	contents=[]
	with open("vsearch.log","r") as log:
		for line in log:
			contents.append([])
			for item in line.split("|"):
				contents[-1] .append(escape(item))
		titles= ["Formdata","Host_url","Remote_addr","Results"]
		return render_template("view.html",the_data=contents,the_titles=titles)



if __name__ == '__main__':
 app.run(debug = True)